import os

import gradio as gr
from tools import chat_free, pdf_summary, chat_pdf

global PDF_PATH

def gradio_chat_free(message, history):
    history = history or []
    gpt_response = chat_free(message, history)
    # Append the user message and the bot response to the history
    history.append((message, gpt_response))
    return "", history

# 定义处理第二个输入框的逻辑的函数
def gradio_chat_pdf(message, history):
    global PDF_PATH  # 声明使用全局变量
    history = history or []
    gpt_response = chat_pdf(message, PDF_PATH)
    # Append the user message and the bot response to the history
    history.append((message, gpt_response))
    return "", history

def gradio_pdf_summary(message, history):
    global PDF_PATH  # 声明使用全局变量
    history = history or []
    gpt_response, PDF_PATH = pdf_summary(message)

    history.append(("一键阅读arxiv论文并生成文章摘要", gpt_response))
    return history, PDF_PATH


# 定义文件上传的逻辑函数
def gradio_file_upload(file_input):
    global PDF_PATH
    # upload_file函数返回处理后的文件路径
    return PDF_PATH


with gr.Blocks(title="智能文献问答系统") as demo:
    gr.HTML("<h1 align=\"center\">智能文献问答系统</h1>")
    # 使用gr.Row将chatbot和Textbox左右分布
    row = gr.Row()
    with row:
        chatbot = gr.Chatbot(height=730, placeholder="Chat here")
        col = gr.Column()
        with col:
            msg = gr.Textbox(label="自由对话")
            clear = gr.ClearButton([msg, chatbot])
            # 添加第二个输入框
            pdf_msg = gr.Textbox(label="pdf问答")
            # 为第二个输入框添加一个提交按钮
            pdf_button = gr.Button("Submit")
            # 将第二个输入框的提交按钮连接到处理函数
            pdf_button.click(gradio_chat_pdf, inputs=[pdf_msg, chatbot], outputs=[pdf_msg, chatbot])

            # 添加第三个输入框
            pdf_down = gr.Textbox(label="pdf下载", placeholder="输入arxiv编号")
            down_button = gr.Button("一键阅读arxiv")
            output_file = gr.File(label="下载文件", height=100)
            down_button.click(gradio_pdf_summary, inputs=[pdf_down, chatbot], outputs=[chatbot, output_file])

    msg.submit(gradio_chat_free, [msg, chatbot], [msg, chatbot], queue=False)

demo.launch()
